<?php
declare(strict_types=1);

namespace SixShop\Message\Model;

use SixShop\Message\Entity\NotificationEntity;
use SixShop\Message\Entity\MessageSettingEntity;
use think\facade\Db;

/**
 * 用户通知模型
 */
class NotificationModel
{
    /**
     * 获取通知列表
     *
     * @param array $params 查询参数
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array
     */
    public function getList(array $params = [], int $page = 1, int $limit = 10)
    {
        $query = NotificationEntity::where('1=1');
        
        // 用户ID筛选
        if (!empty($params['user_id'])) {
            $query->where('user_id', $params['user_id']);
        }
        
        // 标题搜索
        if (!empty($params['title'])) {
            $query->where('title', 'like', '%' . $params['title'] . '%');
        }
        
        // 类型筛选
        if (isset($params['type']) && $params['type'] !== '') {
            $query->where('type', $params['type']);
        }
        
        // 是否已读筛选
        if (isset($params['is_read']) && $params['is_read'] !== '') {
            $query->where('is_read', $params['is_read']);
        }
        
        // 时间范围筛选
        if (!empty($params['start_time'])) {
            $query->where('create_time', '>=', strtotime($params['start_time']));
        }
        if (!empty($params['end_time'])) {
            $query->where('create_time', '<=', strtotime($params['end_time']));
        }
        
        // 获取总数
        $total = $query->count();
        
        // 获取分页数据
        $list = $query->order('id', 'desc')
            ->page($page, $limit)
            ->select()
            ->toArray();
        
        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
        ];
    }
    
    /**
     * 获取用户通知列表
     *
     * @param int $userId 用户ID
     * @param array $params 查询参数
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array
     */
    public function getUserNotifications(int $userId, array $params = [], int $page = 1, int $limit = 10)
    {
        $query = MessageNotificationsModel::with(['template'])
            ->where(function ($query) use ($userId) {
            $query->where('user_id', $userId)
                ->whereOr('user_id', 0); // 包括全局通知
        });
        
        // 类型筛选
        if (isset($params['type']) && $params['type'] !== '') {
            $query->where('type', $params['type']);
        }
        
        // 是否已读筛选
        if (isset($params['is_read']) && $params['is_read'] !== '') {
            $query->where('is_read', $params['is_read']);
        }
        
        // 获取总数
        $total = $query->count();
        
        // 获取分页数据
        $list = $query->order('id', 'desc')
            ->page($page, $limit)
            ->select()
            ->toArray();
        
        // 获取未读数量
        $unreadCount = MessageNotificationsModel::where(function ($query) use ($userId) {
            $query->where('user_id', $userId)
                ->whereOr('user_id', 0);
        })->where('is_read', 0)->count();
        
        return [
            'list' => $list,
            'total' => $total,
            'unread_count' => $unreadCount,
            'page' => $page,
            'limit' => $limit,
        ];
    }
    
    /**
     * 获取单个通知详情
     *
     * @param int $id 通知ID
     * @return array|null
     */
    public function getDetail(int $id)
    {
        return NotificationEntity::find($id);
    }
    
    /**
     * 添加通知
     *
     * @param array $data 通知数据
     * @return int|bool
     */
    public function add(array $data)
    {
        $entity = new NotificationEntity();
        $entity->save($data);
        
        return $entity->id;
    }
    
    /**
     * 发送通知给用户
     *
     * @param int $userId 用户ID，0表示全部用户
     * @param string $title 通知标题
     * @param string $content 通知内容
     * @param int $type 通知类型：1-系统通知，2-活动通知，3-订单通知，4-物流通知，5-其他
     * @return int|bool
     */
    public function sendToUser(int $userId, string $title, string $content, int $type = 1)
    {
        // 检查用户的消息设置
        if ($userId > 0) {
            $setting = MessageSettingEntity::where('user_id', $userId)->find();
            if ($setting && !$setting->isNotifyEnabled($type)) {
                // 用户已关闭此类型的通知
                return false;
            }
        }
        
        $data = [
            'user_id' => $userId,
            'title' => $title,
            'content' => $content,
            'type' => $type,
            'is_read' => 0,
            'read_time' => 0,
            'create_time' => time(),
            'update_time' => time(),
        ];
        
        return $this->add($data);
    }
    
    /**
     * 批量发送通知给多个用户
     *
     * @param array $userIds 用户ID数组
     * @param string $title 通知标题
     * @param string $content 通知内容
     * @param int $type 通知类型
     * @return bool
     */
    public function sendToMultiUsers(array $userIds, string $title, string $content, int $type = 1)
    {
        if (empty($userIds)) {
            return false;
        }
        
        $time = time();
        $data = [];
        
        foreach ($userIds as $userId) {
            // 检查用户的消息设置
            $setting = MessageSettingEntity::where('user_id', $userId)->find();
            if ($setting && !$setting->isNotifyEnabled($type)) {
                // 用户已关闭此类型的通知
                continue;
            }
            
            $data[] = [
                'user_id' => $userId,
                'title' => $title,
                'content' => $content,
                'type' => $type,
                'is_read' => 0,
                'read_time' => 0,
                'create_time' => $time,
                'update_time' => $time,
            ];
        }
        
        if (empty($data)) {
            return false;
        }
        
        return Db::name('message_notifications')->insertAll($data);
    }
    
    /**
     * 发送全局通知
     *
     * @param string $title 通知标题
     * @param string $content 通知内容
     * @param int $type 通知类型
     * @return int|bool
     */
    public function sendGlobal(string $title, string $content, int $type = 1)
    {
        return $this->sendToUser(0, $title, $content, $type);
    }
    
    /**
     * 标记通知为已读
     *
     * @param int $id 通知ID
     * @param int $userId 用户ID，用于验证权限
     * @return bool
     */
    public function markAsRead(int $id, int $userId = 0)
    {
        $entity = NotificationEntity::find($id);
        if (!$entity) {
            return false;
        }
        
        // 验证权限
        if ($userId > 0 && $entity->user_id > 0 && $entity->user_id != $userId) {
            return false;
        }
        
        return $entity->markAsRead()->save();
    }
    
    /**
     * 批量标记通知为已读
     *
     * @param array $ids 通知ID数组
     * @param int $userId 用户ID，用于验证权限
     * @return bool
     */
    public function batchMarkAsRead(array $ids, int $userId = 0)
    {
        if (empty($ids)) {
            return false;
        }
        
        $query = NotificationEntity::where('id', 'in', $ids);
        
        // 验证权限
        if ($userId > 0) {
            $query->where(function ($query) use ($userId) {
                $query->where('user_id', $userId)
                    ->whereOr('user_id', 0);
            });
        }
        
        return $query->update([
            'is_read' => 1,
            'read_time' => time(),
        ]);
    }
    
    /**
     * 标记用户所有通知为已读
     *
     * @param int $userId 用户ID
     * @return bool
     */
    public function markAllAsRead(int $userId)
    {
        if ($userId <= 0) {
            return false;
        }
        
        return NotificationEntity::where(function ($query) use ($userId) {
            $query->where('user_id', $userId)
                ->whereOr('user_id', 0);
        })->where('is_read', 0)->update([
            'is_read' => 1,
            'read_time' => time(),
        ]);
    }
    
    /**
     * 删除通知
     *
     * @param int $id 通知ID
     * @param int $userId 用户ID，用于验证权限
     * @return bool
     */
    public function delete(int $id, int $userId = 0)
    {
        $entity = NotificationEntity::find($id);
        if (!$entity) {
            return false;
        }
        
        // 验证权限
        if ($userId > 0 && $entity->user_id > 0 && $entity->user_id != $userId) {
            return false;
        }
        
        return $entity->delete();
    }
    
    /**
     * 批量删除通知
     *
     * @param array $ids 通知ID数组
     * @param int $userId 用户ID，用于验证权限
     * @return bool
     */
    public function batchDelete(array $ids, int $userId = 0)
    {
        if (empty($ids)) {
            return false;
        }
        
        $query = NotificationEntity::where('id', 'in', $ids);
        
        // 验证权限
        if ($userId > 0) {
            $query->where(function ($query) use ($userId) {
                $query->where('user_id', $userId)
                    ->whereOr('user_id', 0);
            });
        }
        
        return $query->delete();
    }
    
    /**
     * 获取用户未读通知数量
     *
     * @param int $userId 用户ID
     * @return int
     */
    public function getUnreadCount(int $userId)
    {
        if ($userId <= 0) {
            return 0;
        }
        
        return NotificationEntity::where(function ($query) use ($userId) {
            $query->where('user_id', $userId)
                ->whereOr('user_id', 0);
        })->where('is_read', 0)->count();
    }
}
